package switchdb

import (
	c "db_ping/config"
	"db_ping/email"
	e "db_ping/err"
	"db_ping/shell"
	"fmt"
	"time"
)

func CloseCommand(keypath, user, host string, port int) {
	cli := shell.NewShellPublicKey("root", "C:\\Users\\dingguangyi\\.ssh\\id_rsa", "39.97.187.111", time.Second, 22)

	defer cli.Close()
	//查询 cul 是否存在
	b, _ := cli.Run("ps -aux|grep md|grep -v grep|awk '{print $2}'")
	//如果存在 kill
	cli.Run("kill -9 " + b)
}

func OpenCommand(keypath, user, host string, port int) {
	cli := shell.NewShellPublicKey("root", "C:\\Users\\dingguangyi\\.ssh\\id_rsa", "39.97.187.111", time.Second, 22)
	//开启
	cli.Run("ps -aux|grep md|grep -v grep|awk '{print $2}'")

}

func SwitchBackDataSource(cfg *c.SqlConfig, r *c.RunSqlConfig) {
	fmt.Println(cfg.TaskName, "切库逻辑执行开始........")
	//查询当前服务环境
	if cfg.Current == "master" {
		s := cfg.SshMaster
		b := cfg.SshBack
		CloseCommand(s.SSHKeyPath, s.UserName, s.Host, s.Port)
		OpenCommand(b.SSHKeyPath, b.UserName, b.Host, b.Port)
	}

	if cfg.Current == "prepare" {

	}
	e.DeleteErrNumber(cfg.TaskName)
	fmt.Println("开始发送告警邮件")
	email.SendEmail("告警", "测试告警")
	//切换db_ping检测主机
	copyProperties(cfg, r)
	fmt.Println(cfg.TaskName, "切库逻辑执行结束........")
}

func copyProperties(cfg *c.SqlConfig, r *c.RunSqlConfig) {
	if cfg.Current == "master" {
		r.Url = cfg.Url
		r.Username = cfg.Username
		r.Password = cfg.Password
		cfg.Current = "prepare"
	}

	if cfg.Current == "prepare" {
		r.Url = cfg.UrlBack
		r.Username = cfg.UsernameBack
		r.Password = cfg.PasswordBack
		cfg.Current = "master"
	}
}
